# -*- coding: utf-8 -*-
__author__ = 'sunnychou'
__date__ = '2019/7/6 13:51'

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication

from email.header import Header
#from config import EMAIL_SETTINGS


EMAIL_SETTINGS = dict(
sender = '18301239320@163.com',
mail_host = 'smtp.163.com',
mail_port = 465,
email_user = "18301239320@163.com",
email_pass = "Favor070801",
receivers = [ "favorit@favor.cc"],
)

class EmailHelper(object):

    @staticmethod
    def  email_login():
        try:
            smtpObj = smtplib.SMTP_SSL(host=EMAIL_SETTINGS['mail_host'])
            smtpObj.connect(EMAIL_SETTINGS['mail_host'], EMAIL_SETTINGS['mail_port'])
            smtpObj.login(EMAIL_SETTINGS['email_user'], EMAIL_SETTINGS['email_pass'])
            #print("邮件连接成功")
            return smtpObj
        except smtplib.SMTPException as e:
            print(f"Error: 无法连接邮件服务器{e}")
            return None


    @staticmethod
    def email_send(smtpObj, subject='SMTP 邮件测试1', mail_msg='', receiver=EMAIL_SETTINGS['receivers']):
        '''
        :param smtpObj: 邮件连接句柄
        :param subject:  邮件主题
        :param mail_msg: 邮件正文
        :param receivers: 接受者列表
        :return:
        '''
        try:
            message = MIMEText(mail_msg, 'html', 'utf-8')
            #message['From'] = Header("飞五科技公共邮箱", 'utf-8')
            #message['To'] = receivers[0]
            message['From'] = EMAIL_SETTINGS['sender']
            message['To'] = ",".join(receiver)
            message['Subject'] = Header(subject, 'utf-8')
            smtpObj.sendmail(EMAIL_SETTINGS['sender'], receiver, message.as_string())
            print("邮件发送成功！")
            return True
        except smtplib.SMTPException as e:
            print(f"Error: email_send 无法发送邮件{e}")
            return False


    @staticmethod
    def email_send_with_appendix(smtpObj, appendix_file_list, subject='SMTP 发送邮件', mail_msg='', receiver=EMAIL_SETTINGS['receivers']):
        '''
        带附件的邮件发送功能, 支持发送多个附件
        :param smtpObj: 邮件连接句柄
        :param appendix_file_list: 发送的附件列表   eg：产品经理.xls
        :param subject:  邮件主题
        :param mail_msg: 邮件正文
        :param receivers: 接受者列表
        :return:
        '''
        try:
            message = MIMEMultipart()
            msg_text = MIMEText(mail_msg, 'html', 'utf-8')
            message.attach(msg_text)

            for  appendix_file  in   appendix_file_list:
                xlsx = MIMEApplication(open(appendix_file, 'rb').read())
                xlsx["Content-Type"] = 'application/octet-stream'
                #xlsx.add_header('Content-Disposition', 'attachment', filename=appendix_file)
                attach_file = appendix_file.split("\\")[-1]
                xlsx.add_header('Content-Disposition', 'attachment', filename=attach_file)
                # 把附件添加到msg中
                message.attach(xlsx)

            message['From'] = EMAIL_SETTINGS['sender']
            message['To'] = ",".join(receiver)
            message['Subject'] = Header(subject, 'utf-8')
            smtpObj.sendmail(EMAIL_SETTINGS['sender'], receiver, message.as_string())
            print("邮件发送成功！")
            return True
        except smtplib.SMTPException as e:
            print(f"Error: email_send_with_appendix 无法发送邮件{e}")
            return False


def email_send_with_appendix_list(subject, mail_msg, appendix_file_list):
    '''
    带附件的邮件发送, 支持批量附件发送
    :return:
    '''
    from common.logger_helper import g_wlogger
    try:
        smtpObj = EmailHelper.email_login()
        if smtpObj == None:
            return
        # appendix_file = "产品经理日常考核报表_v2.xlsx"
        # EmailHelper.email_send(smtpObj, subject='产品信息',mail_msg= mail_msg)
        EmailHelper.email_send_with_appendix(smtpObj, appendix_file_list, subject=subject, mail_msg=mail_msg)
        return True
    except Exception as e:
        g_wlogger.werror(f"fv_email_send_with_appendix has error {e},subject:{subject} ")
        return False


def test_email():
    mail_msg = """
    <p>来自于我们的邮箱信息</p>
    <p><a href="http://www.runoob.com">这是一个链接</a></p>
    """

    smtpObj = EmailHelper.email_login()
    if smtpObj == None:
        return
    appendix_file = "产品经理日常考核报表_v2.xlsx"
    #EmailHelper.email_send(smtpObj, subject='产品信息',mail_msg= mail_msg)
    EmailHelper.email_send_with_appendix(smtpObj, appendix_file, subject='产品信息',mail_msg= mail_msg)


if __name__ == "__main__":

    subject = "统计报表"
    mail_msg = "k3的邮件信息"
    filename = "采购订单-2018-01.xls"
    #path = "F:\\Tx_Project\\favor_data_analyse\\favor_new_data_report\\k3_data_report\\export_tables"
    path = "E:\\favor_project"
    #appendix_files = [f"{path}\\客户信息-2019-07.xls", f"{path}\\品牌.xlsx"]
    appendix_files = [f'{path}\\{filename}']
    email_send_with_appendix_list(subject, mail_msg, appendix_files)

    # for afile in appendix_files:
    #     afilelist = afile.split("\\")
    #     mfilename = afilelist[-1]
    #     print(mfilename)